import cloud.tianai.nio.channel.Channel;
import cloud.tianai.nio.channel.NioServerSocketChannel;
import cloud.tianai.nio.channel.NioSocketChannel;
import cloud.tianai.nio.handler.ChannelHandlerContext;
import cloud.tianai.nio.handler.ChannelInboundHandler;
import cloud.tianai.nio.handler.ChannelOutboundHandler;
import cloud.tianai.nio.loop.NioEventLoopGroup;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class ServerDemo {


    public static void main(String[] args) throws InterruptedException, IOException {
        NioEventLoopGroup eventLoops = new NioEventLoopGroup(1);
        NioEventLoopGroup eventLoops2 = new NioEventLoopGroup(5);
        NioServerSocketChannel socketChannel = new NioServerSocketChannel();
        eventLoops.register(socketChannel);
        socketChannel.bind(new InetSocketAddress(9999));
        socketChannel.getPipeline()
                .addLast((ChannelInboundHandler) (ctx, msg) -> {
                    final Channel child = (Channel) msg;
                    child.getPipeline()
                            .addLast((ChannelOutboundHandler) (c, m) -> {
                                c.write(StandardCharsets.UTF_8.encode((String) m));
                            })
                            .addLast((ChannelInboundHandler) (c, m) -> {
                                c.fireChannelRead(StandardCharsets.UTF_8.decode((ByteBuffer) m).toString());
                            })
                            .addLast(new ChannelInboundHandler2());
                    eventLoops2.register(child);
                });


        System.out.println("started -> " + 9999);
        TimeUnit.DAYS.sleep(1L);
    }


    public static class ChannelInboundHandler2 implements ChannelInboundHandler {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("read==========" + msg);

            NioSocketChannel channel = (NioSocketChannel) ctx.channel();
            channel.write("server收到:" + msg);
//            javaChannel.close();
//            ctx.fireChannelRead(msg);

        }

    }
}
